package com.yunhe.tianhe.rentcars.controller.zuche;

import com.alibaba.fastjson.JSON;
import com.yunhe.tianhe.commons.util.ConfigUtils;
import com.yunhe.tianhe.rentcars.dto.JSONResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Controller
@RequestMapping
public class StorageController {

    /**
     * 文件上传
     * @param req
     * @param resp
     * @return
     * @throws IOException
     * @throws ServletException
     */
    @ResponseBody
    @RequestMapping("/upload")
    public JSONResponse upload(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        List<String> srcList = new ArrayList<>();   //存放所有上传文件的路径
        Collection<Part> parts = req.getParts();  // 获取上传的文件集合
        File baseDir = new File("E:\\fs\\");   //  读取上传文件的根目录
        if(!baseDir.exists()) {
            baseDir.mkdirs();
        }

        for(Part part : parts) {
            String submittedFileName = part.getSubmittedFileName();   //获取文件的原始名称
            String suffix = submittedFileName.substring(submittedFileName.lastIndexOf("."));  //获取文件后缀名
            String fileName = System.currentTimeMillis() + suffix ;  // 时间戳+后缀名 组成新文件名称，避免文件名重复
            part.write(baseDir + fileName);   //将文件写入指定目录
            srcList.add(fileName);
        }
        //返回Json
        JSONResponse result = JSONResponse.success("上传成功", srcList);
        return result;
    }

    @RequestMapping("/dl/img")
    public void download(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String baseDir = ConfigUtils.readValue("fs.baseDir");   //  读取上传文件的根目录
        String fileName = req.getParameter("path");  //所要加载的图片名称
        File file = new File(baseDir + fileName);
        resp.setCharacterEncoding("utf-8");
        if(file.exists()) {
            //.将要下载的文件读入内存
            InputStream fileInputStream = new FileInputStream(file);
            ServletOutputStream outputStream = resp.getOutputStream();  //获得输出流 进行下载
            byte[] buff = new byte[1024*1024];
            int len ;
            while ((len = fileInputStream.read(buff)) != -1){
                outputStream.write(buff,0,len);
            }
            outputStream.flush();
            outputStream.close();
        }
    }

    /**
     * 以附件形式下载文件
     * @param req
     * @param resp
     * @throws IOException
     */
    @RequestMapping("/dl/file")
    public void dlFile(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String baseDir = ConfigUtils.readValue("fs.baseDir");   //  读取上传文件的根目录
        String fileName = req.getParameter("path");  //所要加载的图片名称
        String dlName = req.getParameter("name");  // 下载的文件附件名称
        File file = new File(baseDir + fileName);
        resp.setCharacterEncoding("utf-8");
        String encodeFileName = URLEncoder.encode(dlName, "UTF-8"); //解决中文名称下载时 乱码问题
        resp.setHeader("content-disposition","attachment;filename=" + encodeFileName); // 让浏览器以附件的形式下载文件，并指定文件名称
        if(file.exists()) {
            //.将要下载的文件读入内存
            InputStream fileInputStream = new FileInputStream(file);
            ServletOutputStream outputStream = resp.getOutputStream();  //获得输出流 进行下载
            byte[] buff = new byte[1024*1024];
            int len ;
            while ((len = fileInputStream.read(buff)) != -1){
                outputStream.write(buff,0,len);
            }
            outputStream.flush();
            outputStream.close();
        }
    }



}
